package DGWeb.Servlets;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.SingleThreadModel;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.tomcat.dbcp.dbcp.BasicDataSource;

import com.google.gson.Gson;

import DGWeb.AppConstants;
import DGWeb.Model.User;

/**
 * Servlet implementation class User_Handler
 */
@SuppressWarnings("deprecation")
@WebServlet("/User_Handler")
public class User_Handler extends HttpServlet implements SingleThreadModel {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public User_Handler() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		HttpSession UserSession = request.getSession();
		InputStreamReader isr = new InputStreamReader(request.getInputStream());
		BufferedReader br = new BufferedReader(isr);
		StringBuilder jsonFileContent = new StringBuilder();
		//read line by line from file
		String nextLine = br.readLine();
		jsonFileContent.append(nextLine);
		// close Buffers
		br.close();
		isr.close();
		
		Boolean Reg = jsonFileContent.toString().contains("registration"); // true if it has this sub string
		Boolean Log = jsonFileContent.toString().contains("Login");
		Context context = null;
		if (Reg)
		{
			Gson json = new Gson();
			User U = json.fromJson(jsonFileContent.toString(), User.class);
			if (U.getPhoto() == null){
				U.setPhoto("imgs/default_pic.jpg");
			}
			
			String[] dt = AppConstants.USERS_INSERT.split("//");
			String exec = dt[0]+U.getUsername()+dt[1]+U.getPassword()+dt[2]+ U.getNickname() +dt[3] +U.getEmail() + dt[4] + U.getDescription() + dt[5] + U.getPhoto() + dt[6];

			try {
				context = new InitialContext();
				BasicDataSource ds = (BasicDataSource)context.lookup(AppConstants.DB_DATASOURCE);
	    		Connection conn = ds.getConnection();
	    		
	    		//create Customers table
				Statement stmt = conn.createStatement();
				//for insert
				stmt.executeUpdate(exec);
				
				//commit update
	    		conn.commit();
	    		stmt.close();
	    		conn.close();
	    		context.close();
	    		
    			UserSession.setAttribute("Username",U.getUsername() );
    			UserSession.setAttribute("Nickname",U.getNickname() ); 
    			UserSession.setMaxInactiveInterval(3600); // 1 Hour is seconds
    			out.print("main.html");
    			
			} catch (NamingException |SQLException e) {
				e.printStackTrace();
				UserSession.invalidate();
				out.print("Failed");
				out.close();
			} 

		} else if ( Log ) {
			String FoundUser = null,FoundPass=null, FoundNickname= null;
			Gson json = new Gson();
			User U = json.fromJson(jsonFileContent.toString(), User.class);
			/*
			String[] DataArray = jsonFileContent.toString().split(",");
			DataArray[0] = DataArray[0].substring(2); // Delete the {" from the begining of the string 
			User U = new User();
			String[] temp = DataArray[0].split(":");
			U.setUsername( (String)temp[1].subSequence(1, temp[1].length()-1));
			temp = DataArray[1].split(":");
			U.setPassword( (String)temp[1].subSequence(1, temp[1].length()-1));
			String exec2= "SELECT Username,Password,Nickname FROM USERS where Username='"+U.getUsername()+"' ";
			*/
			try {
				context = new InitialContext();
				BasicDataSource ds = (BasicDataSource)context.lookup(AppConstants.DB_DATASOURCE);
				Connection conn = ds.getConnection();
				//create Customers table
				Statement stmt = conn.createStatement();
				// build the sql command
				String[] dt = AppConstants.USERS_SELECT_FIND_USER.split("//");
				String exec = dt[0]+ U.getUsername() +dt[1];
				// preform the SQL Select Command
				ResultSet res = stmt.executeQuery(exec);
				
				
				while(res.next()) // Get the Parameters if its exist
				{
	    			FoundUser = res.getString(AppConstants.USERNAME);
	    			FoundPass = res.getString(AppConstants.PASSWORD);
	    			FoundNickname = res.getString(AppConstants.NICKNAME);
				}
			
				//commit update
	    		conn.commit();
	    		stmt.close();
	    		conn.close();
	    		context.close();
	    		
	    		if ( FoundUser != null && FoundUser.equals(U.getUsername()) && FoundPass!=null && FoundPass.equals( U.getPassword())){
     
        			UserSession.setAttribute(AppConstants.USERNAME,U.getUsername() );
        			UserSession.setAttribute(AppConstants.NICKNAME, FoundNickname  );
        			UserSession.setMaxInactiveInterval(3600); // 60 minutes * 60 seconds
	    			out.print("main.html");
	    			
	        	}
        		else
        		{
        			UserSession.invalidate();
        			out.print("Failed");
        		}
	    		
	    		
			} catch (NamingException |SQLException e) {
			
				e.printStackTrace();
				out.close();
				UserSession.invalidate();
			}
		}//
		out.close();
	} // end do post
	
}
